<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/mysql/MySQL体系结构/">
  <title>
    
      MySQL体系结构 - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#数据库" title="数据库">数据库</a>
              
              <a class="tag" href="/tags/#mysql" title="mysql">mysql</a>
              
            </div>
            <h1>MySQL体系结构</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2020-04-18
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">10</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">3k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <h2 id="一、一条查询SQL语句是如何执行的"><a href="#一、一条查询SQL语句是如何执行的" class="headerlink" title="一、一条查询SQL语句是如何执行的"></a>一、一条查询SQL语句是如何执行的</h2><p>首先，数据库是存储在MySQL服务端的，应用程序或者工具都是客户端，客户端要读写数据库，第一步要与数据库服务器建立连接</p>
<h3 id="1-通信协议"><a href="#1-通信协议" class="headerlink" title="1. 通信协议"></a>1. 通信协议</h3><h4 id="1-1-通信协议"><a href="#1-1-通信协议" class="headerlink" title="1.1 通信协议"></a>1.1 通信协议</h4><ul>
<li>通信类型：同步或者异步</li>
</ul>
<p>一般来说客户端连接数据库都是同步连接</p>
<ul>
<li>连接方式：长连接或短连接</li>
</ul>
<p>MySQL既支持短连接，也支持长连接。对于长连接，会把连接放入客户端的连接池中。</p>
<p>可以通过SHOW STATUS命令查看MySQL当前有多少个连接：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SHOW</span> <span class="keyword">GLOBAL</span> STATUS <span class="keyword">LIKE</span> <span class="string">&#x27;Thread%&#x27;</span>;</span><br></pre></td></tr></table></figure>
<p>每产生一个连接或者一个会话，在服务器就会创建一个线程来处理</p>
<p><img src="image-20200418192228143.png" alt="image-20200418192228143"></p>
<div class="table-container">
<table>
<thead>
<tr>
<th>字段</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>Threads_cached</td>
<td>缓存中的线程连接数</td>
</tr>
<tr>
<td>Threads_connected</td>
<td>当前打开的连接数</td>
</tr>
<tr>
<td>Threads_created</td>
<td>为处理连接创建的线程数</td>
</tr>
<tr>
<td>Threads_running</td>
<td>非睡眠状态的连接数，通常指并发连接数</td>
</tr>
</tbody>
</table>
</div>
<p>保持长连接会消耗内存，长时间不活动的连接，MySQL服务器会断开。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">show</span> <span class="keyword">global</span> variables <span class="keyword">like</span> <span class="string">&#x27;wait_timeout&#x27;</span>; <span class="comment">-- 非交互式超时时间，如 JDBC 程序</span></span><br><span class="line"><span class="keyword">show</span> <span class="keyword">global</span> variables <span class="keyword">like</span> <span class="string">&#x27;interactive_timeout&#x27;</span>; <span class="comment">-- 交互式超时时间，如数据库工具</span></span><br></pre></td></tr></table></figure>
<p><img src="image-20200418192823635.png" alt="image-20200418192823635"></p>
<p>默认为都是28800秒，8个小时</p>
<p>MySQL服务允许的最大连接数默认是200个</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">show</span> variables <span class="keyword">like</span> <span class="string">&#x27;max_connections&#x27;</span>;</span><br></pre></td></tr></table></figure>
<p><img src="image-20200419105614212.png" alt="image-20200419105614212"></p>
<p>参数级别说明：</p>
<p>MySQL中的参数分为session和global级别，分别是在当前会话中生效和全局生效，但是并不是每个参数都有两个级别，比如<code>max_connections</code>就只有全局级别。</p>
<p>当没有带参数的时候，默认的是session级别，包括查询和修改</p>
<p>比如修改一个参数以后，在本窗口查询已经生效，但是其他窗口不生效：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SHOW</span> VARIABLES <span class="keyword">LIKE</span> <span class="string">&#x27;autocommit&#x27;</span>;</span><br><span class="line"><span class="keyword">SET</span> autocommit <span class="operator">=</span> <span class="keyword">ON</span>;</span><br></pre></td></tr></table></figure>
<h4 id="1-2-通信方式"><a href="#1-2-通信方式" class="headerlink" title="1.2 通信方式"></a>1.2 通信方式</h4><p><img src="image-20200419110458271.png" alt="image-20200419110458271"></p>
<ul>
<li>单工：在两台计算机通信的时候，数据的传输是单向的。</li>
<li>半双工：在两台计算机之间，数据传输是双向的，你可以给我发送，我也可以给你发送，但是在通讯连接里面，同一时间只能有一台服务器在发送数据，也就是你给我发送，必须等我发送完之后才能给我发。</li>
<li>全双工：数据的传输是双向的，并且可以同时传输。</li>
</ul>
<p>MySQL使用了半双工的通信方式，在一个链接中，要么是客户端向服务器端发送数据，要么是服务器向客户端发送数据，不能同时发生。所以客户端发送SQL语句给服务器端的时候，数据是不能分成小块发送的，不管你的SQL语句有多大，都是一次性发送。</p>
<p>比如用MyBatis动态SQL生成批量插入的语句，values后面跟了一长串，或者where条件in里面的值太多，会出现问题。</p>
<p>调整MySQL服务器配置<code>max_allowed_packet</code>参数的值，把它调大。</p>
<p><img src="image-20200419111839790.png" alt="image-20200419111839790"></p>
<p>另一方面，对于服务器端，也是一次性发送所有的数据，不能中断操作，会对网络和内存产生大量消耗，在程序中要避免不带LIMIT的操作。</p>
<h3 id="1-2-查询缓存"><a href="#1-2-查询缓存" class="headerlink" title="1. 2 查询缓存"></a>1. 2 查询缓存</h3><p>MySQL内部自带缓存模块。MySQL的缓存默认是关闭的，并且在MySQL 8.0以上，查询缓存以及被移除了。</p>
<h3 id="1-3-语法解析和预处理（Parser-amp-Preprocessor）"><a href="#1-3-语法解析和预处理（Parser-amp-Preprocessor）" class="headerlink" title="1. 3 语法解析和预处理（Parser &amp; Preprocessor）"></a>1. 3 语法解析和预处理（Parser &amp; Preprocessor）</h3><p>对SQL语句进行词法和语法分析和语义的解析，是Parser解析器和Preprocessor预处理模块。</p>
<h4 id="1-3-1-词法解析"><a href="#1-3-1-词法解析" class="headerlink" title="1.3.1 词法解析"></a>1.3.1 词法解析</h4><p>词法分析就是把一个完整的SQL语句打碎成一个个的单词，每个符号是什么类型，从哪里开始到哪里结束。</p>
<h4 id="1-3-2-语法解析"><a href="#1-3-2-语法解析" class="headerlink" title="1. 3.2 语法解析"></a>1. 3.2 语法解析</h4><p>第二步就是语法解析，语句分析会对SQL做一些语法检查，比如单引号有没有闭合，然后根据MySQL定义的语法规则，根据SQL语句生成一个数据结构（解析树）。</p>
<p><img src="image-20200419113950804.png" alt="image-20200419113950804"></p>
<p>词法语法分析是一个非常基础的功能，编译器，搜索引擎如果要识别语句，必须也要有词法语法分析功能。</p>
<h4 id="1-3-3-预处理"><a href="#1-3-3-预处理" class="headerlink" title="1 .3.3 预处理"></a>1 .3.3 预处理</h4><p>如果写了一个词法和语法都正确的SQL，但是表名或者字段不存在，是在解析时候报错，因为解析SQL的环节里面有预处理，它会检查生成的解析树，解决解析器无法解析的语义。比如，会检查表和列名是否存在，检查名字和别名，保证没有歧义。</p>
<p>预处理之后得到一个新的解析树</p>
<h3 id="1-4-查询优化（Query-Optimizer）与查询执行计划"><a href="#1-4-查询优化（Query-Optimizer）与查询执行计划" class="headerlink" title="1. 4 查询优化（Query Optimizer）与查询执行计划"></a>1. 4 查询优化（Query Optimizer）与查询执行计划</h3><h4 id="1-4-1-什么是优化器？"><a href="#1-4-1-什么是优化器？" class="headerlink" title="1. 4.1 什么是优化器？"></a>1. 4.1 什么是优化器？</h4><p>解析树是一个可以被执行器认识的数据结构。</p>
<p>一条SQL语句是不是只有一种执行方式？或者说数据库最终执行的SQL是不是就是发送的SQL？</p>
<p>答案时是否定的。一条SQL语句是可以有很多种执行方式的，最终返回相同的结果，它们是等价的。但是如果有这么多中执行方式，这些执行方式怎么得到的？最终选择哪一种去执行？根据什么判断标准去选择？</p>
<p>这个就是MySQL的查询优化器的模块。</p>
<p>查询优化器的目的就是根据解析树生成不同的执行计划，然后选择一种最优的执行计划，MySQL里面使用的是基于开销的优化器，哪种执行计划开销最小，就用哪种。</p>
<p><img src="image-20200419153633285.png" alt="image-20200419153633285"></p>
<h4 id="1-4-2-优化器可以做什么？"><a href="#1-4-2-优化器可以做什么？" class="headerlink" title="1. 4.2 优化器可以做什么？"></a>1. 4.2 优化器可以做什么？</h4><p>MySQL的优化器能处理哪些优化类型呢？</p>
<p>举两个简单的例子：</p>
<ol>
<li>当我们对多张表进行关联查询的时候，以哪个表的数据作为基准表（先访问哪张表）</li>
<li>有多个索引可以使用，选择哪个索引</li>
<li>对于查询条件的优化，比如移除1=1之类的恒等式，移除不必要的括号，表达式的计算，子查询和连接查询的优化。</li>
</ol>
<p>经过优化器处理之后，得到一个什么东西？</p>
<h4 id="1-4-3-优化器得到的结果"><a href="#1-4-3-优化器得到的结果" class="headerlink" title="1.4.3 优化器得到的结果"></a>1.4.3 优化器得到的结果</h4><p>优化器最终会把解析树变成一个<code>执行计划</code>,执行技术也是一个数据结构，这个执行计划也不一定是最优的执行计划。</p>
<p>如何查看MySQL的执行计划？</p>
<p><code>在SQL前加上EXPLAIN</code>,想要看到详细的信息，还可以用<code>FORMAT=JSON</code></p>
<h3 id="1-5存储引擎"><a href="#1-5存储引擎" class="headerlink" title="1.5存储引擎"></a>1.5存储引擎</h3><h4 id="1-5-1-存储引擎基本介绍"><a href="#1-5-1-存储引擎基本介绍" class="headerlink" title="1.5.1 存储引擎基本介绍"></a>1.5.1 存储引擎基本介绍</h4><p>表在存储数据的同时，还要组织数据的存储结构，这个存储结构就是由我们的存储引擎决定的，也把存储引擎叫做表类型。</p>
<p>在MySQL里面，支持多种存储引擎，可以替换。</p>
<p>存储引擎的使用是以表为单位的（表类型），在创建表之后还可以修改存储引擎。</p>
<h3 id="1-6-执行引擎，返回结果"><a href="#1-6-执行引擎，返回结果" class="headerlink" title="1.6 执行引擎，返回结果"></a>1.6 执行引擎，返回结果</h3><p>执行器，或者叫执行引擎，利用存储引擎提供的相应的API来完成操作，最后把数据返回给客户端，即时没有结果也要返回</p>
<h2 id="二、MySQL体系结构"><a href="#二、MySQL体系结构" class="headerlink" title="二、MySQL体系结构"></a>二、MySQL体系结构</h2><h3 id="2-1-模块详解"><a href="#2-1-模块详解" class="headerlink" title="2.1 模块详解"></a>2.1 模块详解</h3><p><img src="image-20200419162752475.png" alt="image-20200419162752475"></p>
<ul>
<li>Connectors：用来支持各种语言和SQL的交互，如Java的JDBC</li>
<li>Management Services &amp; Utilities：系统管理和控制工具，包括备份恢复，MySQL复制、集群等等；</li>
<li>Connection Pool：连接池，管理需要缓冲的资源，包括用户名密码权限线程等。</li>
<li>SQL Interface：用来接收用户的SQL命令，返回用户需要的查询结果</li>
<li>Parser：用来解析SQL语句</li>
<li>Optimizer：查询优化器</li>
<li>Caches &amp; Buffers：查询缓存</li>
<li>Pluggable Storage Engines：插件式存储引擎。</li>
</ul>
<h3 id="2-2-架构分层"><a href="#2-2-架构分层" class="headerlink" title="2.2 架构分层"></a>2.2 架构分层</h3><p>MySQL分为两层，执行操作的<code>服务层</code>，和存储管理数据的<code>存储引擎层</code></p>
<p><img src="image-20200419164153832.png" alt="image-20200419164153832"></p>
<p>服务层包括连接器、查询缓存、分析器、优化器、执行器，包括大多数MySQL中的核心功能，所有跨存储引擎的功能在服务层实现，包括存储过程、触发器、视图等</p>
<p>存储引擎层包括MySQL常见的存储引擎，包括MyISAM、InnoDB等。</p>
<h2 id="三、一条更新SQL是如何执行的"><a href="#三、一条更新SQL是如何执行的" class="headerlink" title="三、一条更新SQL是如何执行的?"></a>三、一条更新SQL是如何执行的?</h2><h3 id="3-1-缓冲池-Buffer-Pool"><a href="#3-1-缓冲池-Buffer-Pool" class="headerlink" title="3.1 缓冲池 Buffer Pool"></a>3.1 缓冲池 Buffer Pool</h3><p>对于InnoDB存储引擎来说，数据是放在磁盘上的，存储引擎要操作数据，必须先把磁盘的数据加载到内存里面才可以操作。</p>
<p>预读取，当磁盘上的一块数据被读取，很可能它附近的位置也会马上读取到，这个叫做局部性原理。避免用多少取多少，减少IO操作。</p>
<p>InnoDB设置一个存储引擎从磁盘读取数据到内存的最小的单位，叫做页。操作系统页的大小是4K，在InnoDB中，最小的默认单位是16K，是一个逻辑单位。</p>
<p>InnoDB使用缓存池，把磁盘读取的数据页放入内存区域，下次读取相同的页面，就直接读取，不用再次从磁盘加载，这个内存区域就是Buffer Pool</p>
<p><img src="image-20200419172253531.png" alt="image-20200419172253531"></p>
<p>修改数据的时候，先修改内存缓冲池里面的数据页，内存的数据页和磁盘数据不一致的时候，叫做<code>脏页</code>。</p>
<p>InnoDB有专门的后台线程把Buufer Pool的数据写入磁盘，每隔一段时间就一次性地把多个修改写入磁盘，这个动作叫<code>刷脏</code></p>
<h3 id="3-2-InnoDB内存结构和磁盘结构"><a href="#3-2-InnoDB内存结构和磁盘结构" class="headerlink" title="3.2 InnoDB内存结构和磁盘结构"></a>3.2 InnoDB内存结构和磁盘结构</h3><p><img src="image-20200419172814352.png" alt="image-20200419172814352"></p>
<h4 id="3-2-1-内存结构"><a href="#3-2-1-内存结构" class="headerlink" title="3.2.1 内存结构"></a>3.2.1 内存结构</h4><p>内存结构里面主要是Buffer Pool、Change Buffer、Log Buffer、AHI</p>
<h5 id="1-Buffer-Pool"><a href="#1-Buffer-Pool" class="headerlink" title="1.Buffer Pool"></a>1.Buffer Pool</h5><h5 id="2-（redo）Log-Buffer"><a href="#2-（redo）Log-Buffer" class="headerlink" title="2. （redo）Log Buffer"></a>2. （redo）Log Buffer</h5><p>因为刷脏不是实时的，如果Buffer Pool里面的脏页还没有刷入磁盘，数据库宕机或者重启，数据就会丢失，所以内存的数据必须要有持久化措施。</p>
<p>InnoDB把所有对页面的修改操作专门写入一个日志文件，如果有未同步到磁盘的数据，数据库启动时候，会从日志文件进行恢复操作。事务ACID中D持久化，就是用它实现的。</p>
<p><img src="image-20200419190253249.png" alt="image-20200419190253249"></p>
<p>这个日志文件就是redo log（重做日志），默认2个文件，每个48M</p>
<p><img src="image-20200419190515600.png" alt="image-20200419190515600"></p>
<p>同样是写磁盘，为什么不直接写到db file里面去？为什么先写日志再写磁盘？写日志文件和写到数据文件有什么区别？</p>
<p>如果我们所需要的数据是随机分散在磁盘上不同页的不同扇区中，那么找到相应的数据需要等到磁臂旋转到指定的页，然后盘片寻找到对应的扇区，才能找到我们所需要的一块数据，一次进行此过程直到找完所有数据，这个随机IO，读取数据速度慢。</p>
<p>假设我们已经找到了第一块数据，并且其他所需的数据就在这一块数据后边，那么就不需要重新寻址，可以依次拿到我们所需要的数据，这个叫顺序IO。</p>
<p>刷盘是随机IO，而记录日志是顺序IO，顺序IO效率更高，因此先把修改写入日志文件，在保证了内存数据的安全性的情况下，可以延迟刷盘时机，进而提高系统的吞吐。</p>
<p>redo log有什么特点？</p>
<ul>
<li>redo log是InnoDB存储引擎实现的，并不是所有存储引擎都有。支持崩溃恢复是InnoDB的一个特性。</li>
<li>redo log是物理日志，记录的是“在某个数据页上做了什么修改”；</li>
<li>redo log的大小是固定的，前面的内容会被覆盖，一旦写满，就会触发buffer pool到磁盘的同步，以便腾出空间记录后面的修改</li>
</ul>
<p>redo log的内容主要用于崩溃恢复。磁盘的数据文件，数据来自buffer pook（只有redo log写满了，不能再记录更多内存的数据了，才把buffer pool刷盘，然后覆盖redo log）</p>


        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/mysql/MySQL索引深入剖析/" data-toggle="tooltip" data-placement="top" title="MySQL索引深入剖析">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/面试/复习面试题中遇到的问题/" data-toggle="tooltip" data-placement="top" title="复习面试题中遇到的问题">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#数据库" title="数据库">数据库</a>
            
            <a class="tag" href="/tags/#mysql" title="mysql">mysql</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
